package domain

import (
	"AcsGo/internal/util"
	"fmt"
)

type ReaderCheckDuplicateRequest struct {
	Code             util.Field
	TransactionDate  util.Field
	InstitutionId    util.FieldPrefix
	PatronIdentifier util.FieldPrefix
	IdCardNo         util.FieldPrefix
	Operator         util.FieldPrefix
	OperationType    util.FieldPrefix
}

func HandleReaderCheckDuplicate(str string) (*ReaderCheckDuplicateRequest, error) {
	if str == "" {
		return nil, fmt.Errorf("str is empty")
	}
	util.Code.Value = "91"
	// 9120240802    140954AO|AA|XO370828198706101074|CNtq|XK1
	var query = ReaderCheckDuplicateRequest{
		Code:             util.Code,
		TransactionDate:  util.TransactionDate,
		InstitutionId:    util.InstitutionId,
		PatronIdentifier: util.PatronIdentifier,
		IdCardNo:         util.IdCardNo,
		Operator:         util.Operator,
		OperationType:    util.OperationType,
	}

	length := query.Code.Length + query.TransactionDate.Length
	if len(str) < length {
		return nil, fmt.Errorf("str is too short")
	}

	strTemp := query.Code.GetValue(str)
	strTemp = query.TransactionDate.GetValue(strTemp)
	strTemp = query.InstitutionId.GetValue(strTemp)
	strTemp = query.PatronIdentifier.GetValue(strTemp)
	strTemp = query.IdCardNo.GetValue(strTemp)
	strTemp = query.Operator.GetValue(strTemp)
	_ = query.OperationType.GetValue(strTemp)
	return &query, nil
}

type ReaderCheckDuplicateResponse struct {
	Code             util.Field
	TransactionDate  util.Field
	InstitutionId    util.FieldPrefix
	PatronIdentifier util.FieldPrefix
	IdCardNo         util.FieldPrefix
	ST               util.FieldPrefix
	OperationType    util.FieldPrefix
	OK               util.FieldPrefix
	TerminalPassword util.FieldPrefix
	MY               util.FieldPrefix
	ScreenMessage    util.FieldPrefix
	PrintLine        util.FieldPrefix
}

func (q ReaderCheckDuplicateResponse) StringFormat() (string, error) {
	sb, err := util.ConcatenateFields(q)
	if err != nil {
		return "", err
	}
	return sb, nil
}

func InitReaderCheckDuplicateResponseResponse(rdbm, sfzh, ok, xk, ac string) *ReaderCheckDuplicateResponse {
	// 9220240623    182658AO|AA|XO371521199005150927|ST|XK1|OK1|AC0|MY0|AF查重验证该读者信息成功!|AG查重验证该读者信息成功!
	util.Code.Value = "92"
	util.TransactionDate.Value = util.GetCurrentTimeInFormat()
	util.IdCardNo.Value = sfzh
	util.OperationType.Value = xk
	util.OK.Value = ok
	util.TerminalPassword.Value = ac
	util.MY.Value = "0"
	util.ScreenMessage.Value = "查重验证该读者信息成功!"
	util.PrintLine.Value = "查重验证该读者信息成功!"
	util.PatronIdentifier.Value = rdbm

	var queryResponse = ReaderCheckDuplicateResponse{
		Code:             util.Code,
		TransactionDate:  util.TransactionDate,
		PatronIdentifier: util.PatronIdentifier,
		IdCardNo:         util.IdCardNo,
		ST:               util.ST,
		OperationType:    util.OperationType,
		OK:               util.OK,
		TerminalPassword: util.TerminalPassword,
		MY:               util.MY,
		ScreenMessage:    util.ScreenMessage,
		PrintLine:        util.PrintLine,
	}

	return &queryResponse
}
